import React, {Component} from 'react';
import store from "../../redux/store";
import {createDecrementAction, createIncrementAction, creatIncrementActionAsync} from "../../redux/count_action";


class Count extends Component {
  /*state = {
    num: 0
  }*/

  /*
  也可以在index.js中定义store,subscribe, 重新调用ReactDOM.render()。由于dom的diff算法存在，不会造成大面积dom更新
   */
  componentDidMount() {
    // store订阅一个更新状态完毕的回调，完成组件的重新渲染
    store.subscribe(() => {
      this.setState({});
    })
  }

  increment = () => {
    const {value} = this.selectedNum
    /*store.dispatch({
      type: 'increment',
      data: value * 1
    })*/
    // 使用action creator
    store.dispatch(createIncrementAction(value * 1))
  }
  decrement = () => {
    const {value} = this.selectedNum
    /*store.dispatch({
      type: 'decrement',
      data: value * 1
    })*/
    store.dispatch(createDecrementAction(value * 1))
  }
  incrementIfOdd = () => {
    // const {num} = this.state
    const num = store.getState();
    if (num % 2) {
      const {value} = this.selectedNum
      /*this.setState(() => ({
        num: num + value * 1
      }))*/
      /*store.dispatch({
        type: 'increment',
        data: value * 1
      })*/
      store.dispatch(createIncrementAction(value * 1))
    }
  }
  incrementAsync = () => {
    // const {num} = this.state
    const {value} = this.selectedNum
    /*setTimeout(() => {
      /!*store.dispatch({
        type: 'increment',
        data: value * 1
      })*!/
      store.dispatch(createIncrementAction(value * 1))
    }, 500)*/

    // 异步Action
    store.dispatch(creatIncrementActionAsync(value * 1, 1000))
  }

  render() {
    // const {num} = this.state
    // 获取redux中的状态
    const num = store.getState();
    return (
      <div>
        <h1>当前求和为: {num}</h1>
        <hr/>
        <select name="count" id="count" ref={c => this.selectedNum = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.increment}>increment</button>
        <button onClick={this.decrement}>decrement</button>
        <button onClick={this.incrementIfOdd}>incrementIfOdd</button>
        <button onClick={this.incrementAsync}>incrementAsync</button>
      </div>
    );
  }
}

export default Count;
